package edu.xust.MetadataGenerator.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import edu.xust.MetadataGenerator.domain.Lines;

public class FileHelper {
	private final static Logger logger = LogManager.getLogger(FileHelper.class);
	
	/**
	 * Extract file extension from fileName.
	 * @param fileName
	 * @return
	 */
	public static String getExt(String fileName){
		String ext = "";
		
		int lastIndex = fileName.lastIndexOf(".");
		if(-1 != lastIndex){
			ext = fileName.substring(lastIndex + 1);
		}
		return ext;
	}
	
	public static Lines readLines(File file){
		int lineCount = 0;
		String lines = "";
		Lines res = new Lines(0, lines);
		if(null != file){
			try {
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line = br.readLine();
				while(null != line){
					lineCount++;
					lines += line + "\n";
					line = br.readLine();
				}
				res = new Lines(lineCount, lines);
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		}
		return res;
	}
	
	/**
	 * Remove slash at the end of fileName if there exists slash.
	 * @param fileName
	 * @return
	 */
	public static String removeSlash(String fileName){
		String res = "";
		if(null != fileName){
			if(fileName.endsWith("/") || fileName.endsWith("\\")){
				res = fileName.substring(0, fileName.length() - 1);
			}else{
				res = fileName;
			}
		}
		
		return res;
	}
	
	public static String convertSlash(String fileName){
		String res = "";
		if(null != fileName){
			res = fileName.replace("\\", "/");
		}
		
		return res;
	}
}
